package com.shyroke.daydayzhuansvc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.dto.AppDto;
import com.shyroke.daydayzhuanapi.dto.InviteImgAdminDto;
import com.shyroke.daydayzhuanapi.entity.AppEntity;
import com.shyroke.daydayzhuanapi.entity.InviteImgEntity;
import com.shyroke.daydayzhuanapi.entity.QAppEntity;
import com.shyroke.daydayzhuanapi.entity.QInviteImgEntity;
import com.shyroke.daydayzhuanapi.mapper.InviteImgMapper;
import com.shyroke.daydayzhuandao.respository.InviteImgRepository;
import com.shyroke.daydayzhuansvc.util.Page;
import com.shyroke.daydayzhuansvc.util.TabelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class InviteImgService {

    @Autowired
    private InviteImgRepository repository;
    @Autowired
    private JPAQueryFactory factory;
    @Autowired
    private InviteImgMapper mapper;

    public TabelData<InviteImgAdminDto> page(Page page) {
        QInviteImgEntity e = QInviteImgEntity.inviteImgEntity;
        JPAQuery<InviteImgEntity> query = factory.selectFrom(e);

        QueryResults<InviteImgEntity> queryResults = query
                .offset(PageRequest.of(page.getPage() - 1, page.getLimit()).getOffset()).limit(page.getLimit())
                .orderBy(e.id.desc())
                .fetchResults();

        List<InviteImgAdminDto> list = queryResults.getResults().stream().map(mapper::entityToDto).collect(Collectors.toList());
        return new TabelData(list,(int)queryResults.getTotal());
    }

    public void save(InviteImgAdminDto dto) {
        repository.save(mapper.dtoToEntity(dto));
    }

    public void update(Integer id, InviteImgAdminDto dto) {
        InviteImgEntity entity = repository.findById(id).orElse(null);
        if(entity != null) {
            entity.setDescription(dto.getDescription());
            entity.setUrl(dto.getUrl());
            entity.setImgType(dto.getImgType());
            repository.save(entity);
        }
    }

    public InviteImgAdminDto getOne(Integer id) {
        InviteImgEntity entity = repository.findById(id).orElse(null);
        if(entity != null) {
            return mapper.entityToDto(entity);
        }
        return null;
    }
}
